package android.funtionality;

import java.io.*;

import android.content.Context;
import android.util.Log;

public class DataWritter {
	
	private static final String TAG = DataWritter.class.getName();
	private static final String FILENAME = "UsersData.txt";
	
	public DataWritter () {
		
	}
	
	public void writeToFile (String data, Context currentContext){
		
		try {
			OutputStreamWriter outputStreamWritter = new 
					OutputStreamWriter(currentContext.openFileOutput(FILENAME, Context.MODE_PRIVATE));
			outputStreamWritter.write(data);
			outputStreamWritter.close();
		} 
		catch (IOException e){
			Log.e(TAG, "File write failed: " + e.toString());
		}
	}
	
	public String readFromFile (Context currentContext) {
		String ret = "";
		
		try {
			InputStream inputStream = currentContext.openFileInput(FILENAME);
			
			if(inputStream != null) {
				
				InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
				String receiveString = "";
				StringBuilder stringBuilder = new StringBuilder();
				
				while ( (receiveString = bufferedReader.readLine()) != null){
					stringBuilder.append(receiveString);
				}
				
				inputStream.close();
				ret = stringBuilder.toString();
			}
		}
		catch (FileNotFoundException e){
			Log.e(TAG, "File not found: " + e.toString());
		} catch (IOException e){
			Log.e(TAG, "Can not read file: " + e.toString());
		}
		
		return ret;
	}

}
